package com.sense.kukoo.common.push

import android.app.Application
import android.util.Log
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging

object FcmManager {

    private val TAG: String = javaClass.simpleName

    private var token: String? = null
    private var listener: ((String)->Unit)? = null

    fun init(app: Application){
        Log.i(TAG, "push_token init")
        if (isGoogleServiceSupport(app)) {
            Log.i(TAG, "push_token isGoogleServiceSupport")
            FirebaseMessaging.getInstance().token
                .addOnCompleteListener(OnCompleteListener { task ->
                    if (!task.isSuccessful) {
                        Log.e(TAG, "push_token task.isSuccess failed")
                        return@OnCompleteListener
                    }
                    // Get new FCM registration token
                    val firebaseToken = task.result
                    Log.e(TAG, "push_token firebaseToken=${firebaseToken}")
                    setNewToken(firebaseToken)
                })
        } else {
            Log.e(TAG, "push_token isGoogleServiceSupport=false !!!")
        }
    }

    fun getToken(): String? = token

    fun setNewToken(token: String){
        this.token = token
        listener?.invoke(token)
    }

    fun setListener(l: ((String)->Unit)?){
        listener = l
    }

    private fun isGoogleServiceSupport(app: Application): Boolean{
        val googleApiAvailability = GoogleApiAvailability.getInstance()
        val resultCode = googleApiAvailability.isGooglePlayServicesAvailable(app)
        return resultCode == ConnectionResult.SUCCESS
    }
}